<template>
    <div class="bg">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span>注册账户</span>
                </div>
            </template>
            <el-form ref="formRef" :model="form" :rules="rules" status-icon label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.fullname" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="form.role" placeholder="请选择角色">
                        <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex" autocomplete="off">
                    <el-radio label="男" v-model="form.sex" />
                    <el-radio label="女" v-model="form.sex" />
                </el-form-item>
                <el-form-item label="手机" prop="tel" autocomplete="off">
                    <el-input v-model="form.tel" type="text" />
                </el-form-item>
                <el-form-item label="邮箱" prop="tel" autocomplete="off">
                    <el-input v-model="form.email" type="text" />
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <el-upload class="avatar-uploader" :action="`${host}/upload/common/`" :show-file-list="false"
                        :headers="headers" accept=".jpeg,.png,.jpg" :data="extra" :on-success="handleAvatarSuccess"
                        :on-error="handleUploadError" :before-upload="handleBeforeUpload">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit(formRef)">保存修改</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
      
<script setup>
import { reactive, ref, watchEffect, inject } from 'vue'
import Admin from '@/api/admin';
import Role from '@/api/Role'
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
// import { ElMessage, ElMessageBox } from 'element-plus';
let form = ref({})
//获取form实例化
const formRef = ref()
//加载角色列表
let roles = ref([]);

let host = inject('host');
//获取当前路由参数
let route = useRoute();
//获取router实例对象
let router = useRouter();

//加载管理员信息
let loadInfo = async (id) => {
    let { status, data } = await Admin.info({ id });
    if (status) {
        return data;;
    }
}
//加载角色
let loadList = async () => {
    let { status, msg, data } = await Role.role();
    if (status) {
        return data;
    }
}
//初始化自动执行，自行分析数据，监听依赖变化
watchEffect(async () => {
    //解构参数
    let { id } = route.params;
    try {
        roles.value = await loadList();
        form.value = await loadInfo(id);
        // console.log(form);
    } catch (error) {
        // console.log(error);
    }
})
// 添加token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
// 附加参数
let extra = { type: 'common' };
// 上传成功
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //如果上传成功
    if (status) {
        // 生成图片的地址
        form.value.avatar = src;
        // form.avatar = URL.createObjectURL(uploadFile.raw);
        ElMessage.success(msg);
    } else {
        ElMessage.error(msg);
    }
}
// 上传失败
let handleUploadError = (error, uploadFile) => {
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);
}
const handleBeforeUpload = (rawFile) => {
    // 判断图片格式/^imge\/(jpeg|png|jpg)$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!')
        return false
    }
    //图片大于2MB
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像体积不能大于2MB!')
        return false
    }
    return true
}

const rules = reactive({
    username: [
        // 为空执行上行，输入执行下行
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账户长度3到20', trigger: 'blur' },
    ],
    fullname: [
        { required: true, message: '请输入名字', trigger: 'blur' },
        { min: 3, max: 5, message: '名字长度3到5', trigger: 'blur' },
    ],
    tel: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '请输入正确手机号' },
    ],
    email: [
        { required: true, message: '请输入邮箱' },
        { pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '请输入正确手机号' },
    ],
    avatar: [
        { required: true },
    ],
    sex: [{ required: true, }],
})

//校验提交
function handleSubmit(formEl) {
    //校验整个表单
    formEl.validate(async (valid, fields) => {
        if (valid) {
            //通过校验
            let { status, msg } = await Admin.edit({ ...form.value });
            if (status) {
                // console.log({ ...form.value });
                ElMessage.success(msg);
                router.push('/System/Admin');
            } else {
                ElMessage.error(msg);
            }
        } else {
            //没通过校验
            console.log('校验失败字段', fields);
        }

    })
}
//离开守卫
onBeforeRouteLeave((to, from, next) => {
    formRef.value.validateField('avatar', (valid) => {
        if (!valid) {
            ElMessageBox.confirm('确定离开吗？你有未保存的修改', { type: 'warning' })
                .then(() => {
                    next(true)
                })
                .catch(() => {
                    next(false);
                })
            return;
        }
        //通过校验，放行
        next(true);
    })
})
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>